package com.store.app.utils.http;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpUtils {

    public static final MediaType MEDIA_TYPE_HTML
            = MediaType.parse("text/html; charset=utf-8");
    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");
    public static final MediaType MEDIA_TYPE_JSON
            = MediaType.parse("application/json; charset=utf-8");
    // post: send some data
    public static final MediaType MEDIA_TYPE_URL_ENCODE
            = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    // upload file
    public static final MediaType MEDIA_TYPE_URL_DATA
            = MediaType.parse("multipart/form-data; charset=utf-8");


    private static final OkHttpClient mOkHttpClient = new OkHttpClient();


    static {
        if (mOkHttpClient != null) {
            mOkHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
            mOkHttpClient.setWriteTimeout(15, TimeUnit.SECONDS);
            mOkHttpClient.setReadTimeout(15, TimeUnit.SECONDS);
        }
    }

    public static OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public static void setCache(Context mContext){
        File sdcache = mContext.getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        mOkHttpClient.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
    }

    /**
     * 不会开启异步线程。
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return mOkHttpClient.newCall(request).execute();
    }
    /**
     * 开启异步线程访问网络
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback){
        mOkHttpClient.newCall(request).enqueue(responseCallback);
    }

    public static void enqueue(Request request, final RequestCallBack requestCallBack){
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(final Response respone) throws IOException {
                Handler mainThread = new Handler(Looper.getMainLooper());
                mainThread.post(new Runnable() {
                    @Override
                    public void run() {
                        requestCallBack.onResponse(respone);
                    }
                });
            }

            @Override
            public void onFailure(final Request request, final IOException e) {
                Handler mainThread = new Handler(Looper.getMainLooper());
                mainThread.post(new Runnable() {
                    @Override
                    public void run() {
                        requestCallBack.onFailure(request, e);
                    }
                });
            }
        });
    }

    public static String getStringFromServer(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = execute(request);
        if (response.isSuccessful()) {
            String responseUrl = response.body().string();
            return responseUrl;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    public static FormEncodingBuilder formatParams() {
        FormEncodingBuilder baseBuilder = new FormEncodingBuilder()
                .add("cert", "");
        return baseBuilder;
    }
    /**
     * 为HttpGet 的 url 方便的添加1个name value 参数。
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String attachHttpGetParam(String url, String name, String value){
        return url + "?" + name + "=" + value;
    }


}

